package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 微信工具类
 */
public class WeChatUtils {

    private static final Logger logger = LoggerFactory.getLogger(WeChatUtils.class);

    /**
     * 获取微信access_token
     * @param appId 小程序appid
     * @param secret 小程序密钥
     * @return access_token
     */
    public static String getAccessToken(String appId, String secret) {
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + appId + "&secret=" + secret;

            String response = sendGetRequest(url);
            JSONObject jsonObject = JSON.parseObject(response);

            if (jsonObject.containsKey("access_token")) {
                return jsonObject.getString("access_token");
            } else {
                logger.error("获取access_token失败: " + response);
                return null;
            }
        } catch (Exception e) {
            logger.error("获取access_token异常", e);
            return null;
        }
    }

    /**
     * 生成小程序二维码
     * @param accessToken 微信access_token
     * @param scene 二维码携带的参数
     * @param page 小程序页面路径
     * @return 二维码图片的base64编码或下载链接
     */
    public static byte[] createQRCode(String accessToken, String scene, String page) {
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;

            // 构造请求参数
            JSONObject params = new JSONObject();
            params.put("scene", scene);
            params.put("page", page);
            params.put("width", 430); // 二维码宽度

            return sendPostRequestForBytes(url, params.toJSONString());
        } catch (Exception e) {
            logger.error("生成小程序二维码异常", e);
            return null;
        }
    }

    /**
     * 发送GET请求
     */
    private static String sendGetRequest(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        br.close();

        return response.toString();
    }

    /**
     * 发送POST请求并返回字节数据
     */
    private static byte[] sendPostRequestForBytes(String urlString, String params) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; utf-8");
        conn.setRequestProperty("Accept", "application/octet-stream");
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = params.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        // 使用兼容性更好的方式读取字节数据
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];
        InputStream inputStream = conn.getInputStream();
        while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return buffer.toByteArray();
    }
}
